<template>
  <el-dialog
    title="修改密码"
    :visible="visible"
    width="400px"
    @close="closeDialog"
    @closed="handleClosed">
    <el-form :model="form" :rules="rules" ref="passwordForm" label-width="100px">
      <el-form-item label="原密码" prop="oldPassword">
        <el-input v-model="form.oldPassword" type="password" show-password></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="form.newPassword" type="password" show-password></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" type="password" show-password></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="loading">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  name: 'PasswordDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    // 验证确认密码是否与新密码一致
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.form.newPassword) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    return {
      loading: false,
      form: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入新密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['getUserInfo'])
  },
  methods: {
    // 提交表单
    submitForm() {
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 调用Vuex中的修改密码方法
          this.$store.dispatch('editPassword', {
            id: this.getUserInfo.id,
            oldPassword: this.form.oldPassword,
            newPassword: this.form.newPassword
          }).then(() => {
            this.$message.success('密码修改成功')
            this.closeDialog()
            this.loading = false
          }).catch(() => {
            // 错误信息已在拦截器中处理
            this.loading = false
          })
        }
      })
    },
    // 关闭对话框
    closeDialog() {
      this.$emit('update:visible', false)
    },
    // 对话框关闭时重置表单
    handleClosed() {
      this.$refs.passwordForm.resetFields()
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>